package day20180129.reflect;




import sun.plugin.dom.core.Element;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Created by 14394 on 2018/1/29.
 */
public class TestReflect {

    public static void createService(){

        //创建所有的service对象
        //利用xpath 指定查询条件
        String xpath = "//bean[@type = 'service']";

        //获取所有service类型的节点

        //中途有一些类不知道，暂时用空集表示
        List<Element> serviceNodeList = new LinkedList<>();

        //创建每一个service类型的对象，并存储到临时的内存空间中
        for (Element serviceElement: serviceNodeList){
            //解析属性值
            String id = serviceElement.getAttribute("id");

            String className = serviceElement.getAttribute("class");

            //反射创建对象
            try {
                Object serviceObject = Class.forName(className).newInstance();

                //得到业务对象的类
                Class serviceClass = serviceObject.getClass();

                //保存到临时的map集合中
                Map<String,Object> serviceObjectMap = new HashMap();

                serviceObjectMap.put(id,serviceObject);

                //这里需要调用此service和dao的对象进行组合，利用本身的set方法

                //这里取每一个节点的属性，暂用空集代替
                List<Element> propertyElements = new LinkedList<>();
                for (Element proElement: propertyElements){
                    String fieldName = proElement.getAttribute("name");
                    String refId = proElement.getAttribute("refId");
                    //获取关联的对象,这里暂用空集代替
                    Map<String,Object> daoObjectMap = new HashMap<>();
                    Object daoObject = daoObjectMap.get("refId");

                    //获取对应的方法
                    String methodName = "set" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);
                    //获取对应的属性

                    Field fieldObj = serviceClass.getDeclaredField(fieldName);
                    Class fieldClazz = fieldObj.getType();

                    //获取属性的set方法
                    Method methodObject = serviceClass.getDeclaredMethod(methodName,fieldClazz);

                    //利用反射调用set方法，组合对象关系

                    methodObject.invoke(serviceObject,daoObject);
                }


            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }

    }
}
